﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;

namespace DZJIFC.Model
{
    public static class ManifestResourceLoader
    {
        /// <summary>
        /// 从嵌入资源读取文本。resourcePath 支持 "Shaders/Shader.vert" 或 "Shaders.Shader.vert"。
        /// 若资源在其它程序集，请把那个程序集传进来。
        /// </summary>
        public static string LoadTextFile(string resourcePath, Assembly assembly = null)
        {
            var asm = assembly ?? typeof(ManifestResourceLoader).Assembly;
            var normalized = resourcePath.Replace('\\', '.').Replace('/', '.');

            var names = asm.GetManifestResourceNames();
            var fullName = names.FirstOrDefault(n =>
                n.EndsWith(normalized, StringComparison.OrdinalIgnoreCase));

            if (fullName == null)
            {
                var list = string.Join(Environment.NewLine, names);
                throw new InvalidOperationException( $"找不到嵌入资源：{normalized}\n实际可用的资源名有：\n{list}");
            }

            using var stream = asm.GetManifestResourceStream(fullName)
                ?? throw new InvalidOperationException($"GetManifestResourceStream 返回 null：{fullName}");
            using var reader = new StreamReader(stream);
            return reader.ReadToEnd();
        }
    }
}
